package de.justphil.tcg.tcgserver.rest.validators;

import javax.ws.rs.core.Response;

import de.justphil.tcg.tcgserver.commons.domain.User;
import de.justphil.tcg.tcgserver.commons.domain.wrappers.Credentials;
import de.justphil.tcg.tcgserver.commons.exceptions.TCGException;
import de.justphil.tcg.tcgserver.commons.i18n.Error;
import de.justphil.tcg.tcgserver.commons.management.DataManager;
import de.justphil.tcg.tcgserver.commons.util.StringUtil;

public class NewUserValidator {

	public Credentials validatePost(DataManager dataManager, User newUser) throws TCGException {
		if (StringUtil.isNullOrEmpty(newUser.getUsername())) {
			throw new TCGException(Error.CLIENT_ERROR_NO_USERNAME, Response.Status.BAD_REQUEST);
		}
		
		if (StringUtil.isNullOrEmpty(newUser.getPassword())) {
			throw new TCGException(Error.CLIENT_ERROR_NO_PASSWORD, Response.Status.BAD_REQUEST);
		}
		
		Credentials c = new Credentials(newUser.getUsername(), newUser.getPassword());
		
		if (!StringUtil.isValid(c.getUsername())) {
			throw new TCGException(Error.CLIENT_ERROR_INVALID_CHARS_IN_USERNAME, Response.Status.BAD_REQUEST);
		}
		
		if (c.getUsername().length() < 3) {
			throw new TCGException(Error.CLIENT_ERROR_USERNAME_LESS_THAN_THREE, Response.Status.BAD_REQUEST);
		}
		
		if (c.getUsername().length() > 32) {
			throw new TCGException(Error.CLIENT_ERROR_USERNAME_GREATER_THAN_32, Response.Status.BAD_REQUEST);
		}
		
		User user = dataManager.getUserByUsername(c.getUsername());
		if (user != null) {
			throw new TCGException(Error.CLIENT_ERROR_USERNAME_ALREADY_EXISTS, Response.Status.BAD_REQUEST);
		}
		
		if (c.getPassword().length() < 6) {
			throw new TCGException(Error.CLIENT_ERROR_PASSWORD_LESS_THAN_SIX, Response.Status.BAD_REQUEST);
		}
		
		if (c.getPassword().length() > 32) {
			throw new TCGException(Error.CLIENT_ERROR_PASSWORD_GREATER_THAN_32, Response.Status.BAD_REQUEST);
		}
		
		
		
		
		return c;
	}
	
}
